//
//  QuestionViewController.m
//  安好
//
//  Created by Mac on 14-5-23.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "QuestionViewController.h"
#import "QuestionTableViewCell.h"
#import "QuestionLastTableViewCell.h"

@interface QuestionViewController ()

@end

@implementation QuestionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.edgesForExtendedLayout=UIRectEdgeNone;
    
    [self makeNavBarView1];

    
    self.title = self.symptomname;
    
    self.yesOrNoBgArray = [[NSMutableArray alloc] init];
    
    self.dataArray = [[NSMutableArray alloc] init];

    self.tableView =  [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    if(IOS7_OR_LATER)
//        self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.tag = 100;
    
    [self.view addSubview:self.tableView];
    
    //获取问题和判断结果
    [self loadQuestionWithId:@"0" andSelect:@"0"];
}
#pragma mark - 设置导航条
-(void)makeNavBarView1
{
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    



    
    
}

-(void)leftButtonClicked:(UIButton *)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)rightButtonClicked:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];

    
}

#pragma mark - tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([[[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"diagnoseend"] isEqualToString:@"0"])
    {
        
        
        
        
        
        float rowHeight = [NSString heightForString:[NSString stringWithFormat:@"33. %@", [[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"diagnosecont"]] Size:CGSizeMake(208, 1000) Font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT] Lines:0].size.height;
        if(rowHeight + 12 > (kScreenWidth==414?66*1.2:66))
            return rowHeight + 12.0f;
        return (kScreenWidth==414?66*1.2:66);
    }
    else
    {
        return 50.0 + [NSString heightForString:[[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"diagnosecont"] Size:CGSizeMake(288, 1000) Font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT] Lines:0].size.height;
    }
    return 44;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([[[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"diagnoseend"] isEqualToString:@"0"])
    {
        
        static NSString *cellIdentifier = @"cellIdentifier";
        QuestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (kScreenWidth==414) {
            cellIdentifier = @"cellIdentifier414";
        }else{
            cellIdentifier = @"cellIdentifier";

        }
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if(!cell)
        {
            
            if (kScreenWidth==414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"QuestionTableViewCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"QuestionTableViewCell" owner:self options:nil] objectAtIndex:0];

            }
        }
        
        //cell 上半部分的背景
        cell.cellBg.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#f5f5f5"];
        
        //cell 前面的红色的标记
        cell.flagBg.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#e05c5c"];
        
        cell.contentLabel.text = [NSString stringWithFormat:@"%ld. %@", indexPath.row + 1, [[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"diagnosecont"]];
        cell.contentLabel.textColor = [ClassMethodsViewController colorWithHexString:@"#575757"];
        cell.contentLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE];

        
        if (self.yesOrNoBgArray.count-1==indexPath.row) {
            cell.bgImageView.image = [UIImage imageNamed:@"zicha_select"];
            cell.yesBtn.titleLabel.textColor = [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
            cell.noBtn.titleLabel.textColor = [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
        }else{
            
            if([[self.yesOrNoBgArray objectAtIndex:indexPath.row] isEqualToString:@"0"])
            {
                cell.bgImageView.image = [UIImage imageNamed:@"zicha_select_no"];
                cell.yesBtn.titleLabel.textColor = [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
                cell.noBtn.titleLabel.textColor = [UIColor whiteColor];
            }
            else
            {
                cell.bgImageView.image = [UIImage imageNamed:@"zicha_select_yes"];
                cell.yesBtn.titleLabel.textColor = [UIColor whiteColor];
                cell.noBtn.titleLabel.textColor = [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
            }
            cell.noBtn.userInteractionEnabled = NO;
            cell.yesBtn.userInteractionEnabled = NO;
        }
        
        cell.yesBtn.tag = 300 + indexPath.row;
        [cell.yesBtn addTarget:self action:@selector(yesBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.noBtn.tag = 400 + indexPath.row;
        [cell.noBtn addTarget:self action:@selector(noBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        static NSString *cellIdentifier = @"identifier";
        QuestionLastTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if(!cell)
        {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"QuestionLastTableViewCell" owner:self options:nil] objectAtIndex:0];
        }
        
        cell.titleLabel.textColor = [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
        cell.titleLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE];

        cell.suggestTextview.textColor = [ClassMethodsViewController colorWithHexString:@"#575757"];
        cell.suggestTextview.text = [[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"diagnosecont"];
        cell.suggestTextview.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
        cell.suggestTextview.editable = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

//        cell.backgroundColor = [UIColor redColor];
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
-(void)yesBtnClicked:(UIButton *)button
{
    if(button.tag - 300 == [self.dataArray count] - 1)
    {
        //yesOrNoBgArray 中保存的是是或否 的背景图，
        [self.yesOrNoBgArray replaceObjectAtIndex:button.tag - 300 withObject:@"1"];
        [self.tableView reloadData];
        
        //根据问题的id 和 是或否 获取下一个问题或者反馈结果
        [self loadQuestionWithId:[[self.dataArray objectAtIndex:button.tag - 300] objectForKey:@"diagnoseid"] andSelect:@"1"];
    }
}
-(void)noBtnClicked:(UIButton *)button
{
    if(button.tag - 400 == [self.dataArray count] - 1)
    {
        
        //根据问题的id 和 是或否 获取下一个问题或者反馈结果
        [self loadQuestionWithId:[[self.dataArray objectAtIndex:button.tag - 400] objectForKey:@"diagnoseid"] andSelect:@"0"];
    }
}
//获取问题和判断结果
#pragma mark - 获取问题和判断结果  网络请求
-(void)loadQuestionWithId:(NSString *)diagnoseid andSelect:(NSString *)diagnoseselect
{

    
    
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:self.symptomid forKey:@"symptomid"];
    [dict setObject:diagnoseid forKey:@"diagnoseid"];
    [dict setObject:diagnoseselect forKey:@"diagnoseselect"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,@"/symptom/diagnose"] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
        MyNSLog("%@",responseObject);
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);//失败
        }else{
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                [self.dataArray addObject:[responseObject objectForKey:@"data"]];

            [self.yesOrNoBgArray addObject:@"0"];
            [self.tableView reloadData];
                //tableview 自动滚动到底部
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.dataArray count] - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                
            }else{
                alertContent(@"网络数据格式错误");
            }
            
        }
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        
    }];
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
